package com.kd.service.product;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kd.common.PageResult;
import com.kd.dao.ProductMapper;
        import com.kd.entity.Product;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;



/**
 * 产品服务实现类，继承自 MyBatis-Plus 的 ServiceImpl
 * 1.通过pid找产品
 * 2.插入员工
 * 3.查看所有产品列表，with过滤条件
 * 4修改属性
 * 5.查找该产品，核对 name、sidefork、panel_leg、bottomlayer、leglayout、boardwing、structure、blockheight 这些属性，
 * 订单数据发送给后端，后端根据产品属性搜索产品表里面有没有对应的记录，有则调用里面的金额，无则创建该产品记录，金额由前端估算和后端计算得来，存入数据库内
 * 6.
 *
 */

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Autowired
    ProductMapper productMapper;
    private final Integer INSERT_SUCESS=1;

    // 1. 通过pid找产品
    @Override
    public Product findProductById(Integer pid) {
        return productMapper.selectById(pid);
    }

    // 2. 插入产品
    @Override
    @Transactional
    public boolean insertProduct(Product product) {
        BigDecimal price = calculateProductPrice(product);
        product.setPrice(price);

        return productMapper.insert(product)  == INSERT_SUCESS;
    }

    // 3. 查看所有产品列表，with过滤条件
    @Override
    public PageResult<Product,Integer> findProductsWithFilters(
            Integer cursor,
            Integer limit,
            Integer pid,
            String name,
            Integer sidefork,
            Integer panel_leg,
            Integer customize,
            Integer bottomlayer,
            Integer leglayout,
            Integer boardwing,
            String structure,
            Integer blockheight,
            BigDecimal minPrice,
            BigDecimal maxPrice
            ) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        // 添加过滤条件
        if (pid != null) wrapper.like("pid",  pid);
        if (StringUtils.isNotBlank(name))  wrapper.like("name",  name);
        if (sidefork != null) wrapper.eq("sidefork",  sidefork);
        if (panel_leg != null) wrapper.eq("panel_leg",  panel_leg);
        if (customize != null) wrapper.eq("customize",  customize);
        if (bottomlayer != null) wrapper.eq("t_bottomlayer",  bottomlayer);
        if (leglayout != null) wrapper.eq("t_leglayout",  leglayout);
        if (boardwing != null) wrapper.eq("tf_boardwing",  boardwing);
        if (structure != null) wrapper.eq("f_structure",  structure);
        if (blockheight != null) wrapper.eq("f_blockheight",  blockheight);
        if (minPrice != null) wrapper.ge("price",  minPrice);
        if (maxPrice != null) wrapper.le("price",  maxPrice);
        if (cursor != null && cursor > 0) {
            wrapper.lt("pid",  cursor);
        }
        wrapper.orderByDesc("pid");
        List<Product> products = productMapper.selectList(wrapper.last("LIMIT  " + (limit + 1)));
        boolean hasNext = products.size()  > limit;
        List<Product> resultData = hasNext ? products.subList(0,  limit) : products;
        Integer nextCursor = hasNext && !resultData.isEmpty()  ?
                resultData.get(resultData.size()  - 1).getPid() : null;

        return PageResult.of(resultData,  nextCursor, hasNext, limit);
    }

    @Override
    public PageResult<Product,Integer> findProductsWithFilters(
            Integer cursor,
            Integer limit,
            Integer pid
    ) {
        if (limit == null || limit <= 0) {
            limit = 10;
        }
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        // 添加过滤条件
        if (pid != null) wrapper.like("pid",  pid);
        if (cursor != null && cursor > 0) {
            wrapper.lt("pid",  cursor);
        }
        wrapper.orderByDesc("pid");
        List<Product> products = productMapper.selectList(wrapper.last("LIMIT  " + (limit + 1)));
        boolean hasNext = products.size()  > limit;
        List<Product> resultData = hasNext ? products.subList(0,  limit) : products;
        Integer nextCursor = hasNext && !resultData.isEmpty()  ?
                resultData.get(resultData.size()  - 1).getPid() : null;

        return PageResult.of(resultData,  nextCursor, hasNext, limit);
    }

    // 4. 修改属性
    @Override
    @Transactional
    public boolean updateProduct(Product product) {
        BigDecimal newPrice = calculateProductPrice(product);
        product.setPrice(newPrice);
        return productMapper.updateById(product)  > 0;
    }

    // 5. 查找该产品，核对属性
    @Override
    @Transactional
    public Product matchProduct(Product productParam) {
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("name",  productParam.getName())
                .eq("sidefork", productParam.getSidefork())
                .eq("panel_leg", productParam.getPanel_leg())
                .eq("customize", productParam.getCustomize())
                .eq("t_bottomlayer", productParam.getT_bottomlayer())
                .eq("t_leglayout", productParam.getT_leglayout())
                .eq("tf_boardwing", productParam.getTf_boardwing())
                .eq("f_structure", productParam.getF_structure())
                .eq("f_blockheight", productParam.getF_blockheight());

        return productMapper.selectOne(wrapper);
    }

    /**
     * 7.获取产品统计
     */
    /**
     * 获取产品统计分页数据* @param cursor 分页游标（上一页最后一条记录的psq值）* @param limit 每页条数* @param isNextPage 是否查询下一页* @return 分页结果
     */
    public PageResult<ProductMapper.ProductStats, Integer> getProductStats(
            Integer cursor,
            Integer limit,
            boolean isNextPage) {
        // 参数校验
        if (limit == null || limit <= 0) {
            throw new IllegalArgumentException("分页大小必须大于0");
        }
        // 查询数据（多查1条用于判断是否有下一页）
        List<ProductMapper.ProductStats> statsList = productMapper.selectProductStats(
                cursor,
                limit + 1,
                isNextPage
        );
        // 处理分页结果
        boolean hasMore = statsList.size()  > limit;
        List<ProductMapper.ProductStats> resultList = hasMore ?
                statsList.subList(0,  limit) : statsList;
        // 计算下一游标值
        Integer nextCursor = resultList.isEmpty()  ? null :
                resultList.get(resultList.size()  - 1).getCursor();
        return PageResult.of(resultList,  nextCursor, hasMore, limit);
    }

    // ============ 价格计算方法 ============

    private BigDecimal calculateProductPrice(Product product) {
        boolean isCustomize = product.getCustomize()  != null && product.getCustomize()  == 1;
        BigDecimal totalPrice = BigDecimal.ZERO;

        // 1. 计算基础价格（基于最大边长）
        int maxLength = extractMaxLength(product.getName());
        totalPrice = totalPrice.add(calculateBasePrice(maxLength));

        // 2. 计算面板价格
        totalPrice = totalPrice.add(calculatePanelPrice(product.getPanel_leg(),  isCustomize));

        // 3. 计算腿子价格
        totalPrice = totalPrice.add(calculateLegPrice(
                product.getSidefork(),
                product.getPanel_leg(),
                isCustomize
        ));

        // 4. 计算附加特性价格
        if (product.getT_bottomlayer()  != null && product.getT_bottomlayer()  == 1) {
            totalPrice = totalPrice.add(new  BigDecimal("4")); // 底板拉秤
        }
        if (product.getTf_boardwing()  != null && product.getTf_boardwing()  > 0) {
            totalPrice = totalPrice.add(new  BigDecimal("1")); // 板翼
        }
        if (product.getF_blockheight()  != null && product.getF_blockheight()  != 10) {
            totalPrice = totalPrice.add(new  BigDecimal("2")); // 自定义垫块高度
        }

        return totalPrice.setScale(2,  BigDecimal.ROUND_HALF_UP);
    }

    // 从产品名称中提取最大边长
    private int extractMaxLength(String name) {
        String[] dimensions = name.split("[*xX]");
        try {
            int length = Integer.parseInt(dimensions[0].trim());
            int width = Integer.parseInt(dimensions[1].trim());
            return Math.max(length,  width);
        } catch (Exception e) {
            throw new IllegalArgumentException("产品名称格式不正确，应为'长*宽'格式，如'100*120'");
        }
    }

    // 根据最大边长计算基础价格
    private BigDecimal calculateBasePrice(int maxLength) {
        if (maxLength < 90) return new BigDecimal("18");
        if (maxLength < 100) return new BigDecimal("22");
        if (maxLength < 120) return new BigDecimal("25");
        if (maxLength < 130) return new BigDecimal("26");
        return new BigDecimal("30"); // >=130cm
    }

    // 计算面板价格
    private BigDecimal calculatePanelPrice(Integer panel_leg, boolean isCustomize) {
        if (panel_leg == null) return BigDecimal.ZERO;
        return panel_leg == 0
                ? (isCustomize ? new BigDecimal("15") : BigDecimal.ZERO)
                : (isCustomize ? new BigDecimal("30") : new BigDecimal("3"));
    }

    // 计算腿子价格
    private BigDecimal calculateLegPrice(Integer sidefork, Integer panel_leg, boolean isCustomize) {
        if (sidefork == null || panel_leg == null) return BigDecimal.ZERO;

        if (sidefork == 0) { // 二面叉
            return panel_leg == 0
                    ? (isCustomize ? new BigDecimal("10") : BigDecimal.ZERO)
                    : (isCustomize ? new BigDecimal("20") : new BigDecimal("3"));
        } else { // 四面叉
            return panel_leg == 0
                    ? (isCustomize ? new BigDecimal("15") : BigDecimal.ZERO)
                    : (isCustomize ? new BigDecimal("25") : BigDecimal.ZERO);
        }
    }

}